<template>
  <div>
    <div id="cart-page">
<!--      <div class="one-shop-box" v-for="(shopItem,index) in allList" style="display: none">
        <div class="shop-box">
          <div class="check-box">
            <el-checkbox v-model="shopItem.supplier.select" @change="checkShopSelect($event,shopItem.shop)"
                         :value="shopItem.id"></el-checkbox>
          </div>
          <div class="shop-logo" @click="$router.push('ShopHome?id='+shopItem.supplier.id)">
            <img :src="shopItem.supplier.logo">
          </div>
          <div class="shop-name" v-text="shopItem.supplier.name"
               @click="$router.push('ShopHome?id='+shopItem.supplier.id)"></div>
          <i class="el-icon el-icon-delete-solid" @click="delSupplier(index)"></i>
          <div class="c"></div>
        </div>
        <div class="product-list">
          <div class="item" v-for="(product,_index) in shopItem.productList" :key="_index">
            <div class="left">
              <el-checkbox v-model="productSelectMap[product.id]"
                           @change="changeSelectNums(shopItem.supplier.id)"></el-checkbox>
            </div>
            <div class="right">
              <div class="right-product-image">
                <img :src="product.image" alt="">
              </div>
              <div class="right-product-other">
                <div class="product-name">
                  <span v-text="product.name"></span>
                </div>
                <div class="product-model">
                  <span v-text="getNewPriceModel(product,'model')" @click="chooseModel(product)"></span>
                  <i class="el-icon-arrow-down" v-if="product.model.indexOf(',')>0"></i>
                </div>
                <div class="product-price">
                  <div class="price red" v-text="'￥'+ToMoney(getNewPriceModel(product,'price'))"></div>
                  <div class="nums">
                    <el-input-number controls-position="right" :max="1000" :min="1" v-model="product.nums"
                                     @change="changeProductNums(product)"></el-input-number>
                  </div>
                </div>
                <div class="product-del-button" @click="delItem(product)">
                  <i class="el-icon el-icon-delete-solid"></i>
                </div>
              </div>
              <div class="c"></div>
            </div>
            <div class="c"></div>
          </div>
          <div class="c"></div>
        </div>
      </div>-->
      <!--空数据-->
      <div v-if="allList.length===0"
           style="height: 50px; line-height: 50px; color: #888888; font-size: 16px; text-align: center">未选择商品....
      </div>

      <div v-if="allList.length>0">
        <div class="nav-button" align="left" style=" padding-left: 5px; padding-bottom: 5px;">
          <div class="button-box" v-for="(shopItem,index) in allList" :key="index">
            <i class="el-icon el-icon-view" @click="searchSupplierProduct(shopItem.supplier)"></i>
            <el-button :type="currSupplierId===shopItem.supplier.id?'success':'info'"
                       @click="changeSupplier(shopItem.supplier)" >
              {{ shopItem.supplier.name + '(' + shopItem.productList.length + ')' }}
            </el-button>
            <i class="el-icon el-icon-remove" @click="delSupplier(shopItem.supplier,index)"></i>
          </div>
        </div>
        <el-table
          :data="currProductList"
          border
          height="500"
          style="width: 1170px; margin-left: 5px;">
          <el-table-column
            prop="name"
            label="#"
            align="center"
            width="50">
            <template slot-scope="scope">
              <el-checkbox v-model="productSelectMap[scope.row.id]" @change="calcPrice"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="名称"
            align="center"
            width="430">
          </el-table-column>
          <el-table-column
            prop="name"
            label="图片"
            align="center"
            width="90">
            <template slot-scope="scope">
              <el-image
                style="width: 35px; height: 35px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="model"
            label="型号"
            align="center"
            width="150">
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            align="center"
            width="100">
            <template slot-scope="scope">
              <span class="price-font" v-text="ToMoney(scope.row.price)"></span>
            </template>
          </el-table-column>
          <el-table-column
            prop="nums"
            label="数量"
            align="center"
            width="160">
            <template slot-scope="scope">
              <el-input-number controls-position="right" :max="1000" :min="1" v-model="scope.row.nums"
                               @change="changeProductNums(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button type="danger" @click="delItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="合计"
            align="center">
            <template slot-scope="scope">
              <span class="price-font" v-text="ToMoney((scope.row.price*scope.row.nums).toFixed(2)-0)"></span>
            </template>
          </el-table-column>

        </el-table>

        <div class="other-box">
          <div class="address-disable" v-if="sendType===1 && (currSupplier.province+'-'+currSupplier.city)!==(currAddress.province+'-'+currAddress.city)">
            {{ currSupplier.isSameCitySend===0?'该供应商不提供同城配送':'当前地址无法配送' }}
          </div>
          <div class="address">
            <template v-if="sendType!==2">
              <address-item v-if="currAddress && currAddress.id>0" :show-type="1" :address-data="currAddress" :choose-address-call-back="setAddress"/>
              <el-button type="primary" v-if="!(currAddress && currAddress.id>0)" @click="$router.push('/ShopAddressFormPage?type=create')">暂无地址,添加新地址</el-button>
            </template>
          </div>
          <div class="info">
            <el-input type="textarea" v-model="info" placeholder="请输入备注"></el-input>
          </div>
          <div class="total-box">
            <div v-if="productPrice>0">
            <div class="row">
              <div class="value"><span v-text="ToMoney(productPrice)"></span></div>
              <div class="name">商品金额</div>
              <div class="c"></div>
            </div>
            <div class="row">
              <div class="value"><span v-text="'-'+ToMoney(fullMinusPrice)"></span></div>
              <div class="name">满减</div>
              <div class="c"></div>
            </div>
            <div class="row">
              <div class="value"><span v-text="ToMoney(expressPrice)"></span></div>
              <div class="name">运费</div>
              <div class="c"></div>
            </div>
            <div class="row">
              <div class="value"><span v-text="ToMoney(price)"></span></div>
              <div class="name">合计</div>
              <div class="c"></div>
            </div>
            </div>
          </div>
          <div class="c"></div>
        </div>
          <div align="right" style="width: 1155px; padding-top: 7px">
          <div>
            物流方式:
            <el-select v-model="sendType" @change="getSendData">
              <el-option
                v-for="(item,index) in sendTypeArr"
                v-if="index!==2"
                :key="index"
                :disabled="currSupplier.isSameCitySend===0 && index===1"
                :label="item.name+(index===1?(currSupplier.isSameCitySend===0?'[未开启同城]':''):'')"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
            <div style="padding-top: 3px;" v-if="sendType===1 && (currSupplier.province+'-'+currSupplier.city)===(currAddress.province+'-'+currAddress.city)">
              配送时间:
              <el-select v-model="sendTime">
                <el-option
                  v-for="(item,index) in orderSendTimeInfoList"
                  :key="index"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
            </div>
            <div style="padding-top: 10px;" v-if="sendType===1 && (currSupplier.province+'-'+currSupplier.city)===(currAddress.province+'-'+currAddress.city)">
              配送距离&费用:
              <el-tag type="warning" v-text="sendDistance+'km'"></el-tag>
              <el-tag type="warning" v-text="'￥'+ToMoney(sendPrice)"></el-tag>
            </div>
        </div>
        </div>
        <div align="center" style="width: 1100px" v-if="allList.length!==0">
          <el-button type="primary" v-if="productPrice>0" @click="submit">提交订单</el-button>
        </div>
      </div>
  </div>
</template>

<script>

import AddressItem from './AddressItem'
export default {
  name: 'CartBox',
  components: {AddressItem},
  data: function () {
    return {
      sendDistance:'5km',
      sendPrice:15,
      sendTime:'今天',
      sendType:0,
      sendTypeArr:this.listToArray(dict.OrderSendTypeArr),
      orderSendTimeInfoList:this.listToArray(dict.OrderSendTimeInfoList),
      isShifu: this.CurrUser.isShifu,
      allList: MyCartTools.getAllList(),
      productSelectMap: {},
      productNewModelMap: {},
      selectedNums: 0,
      shopSelectArr: [],
      currSupplierId: 0,
      currProductList: [],
      productPrice: 0,
      expressPrice: 0,
      fullMinusPrice: 0,
      price: 0,
      currSupplier: {},
      currAddress:{},
      info:'',
    }
  },
  mounted () {
    this.handleCacheToList()
    this.getAddress()
  },
  methods: {
    setAddress:function (address) {
      // console.log('address',address)
      this.currAddress=address
      this.getSendData()
      this.$forceUpdate()
    },
    getSendData:function () {
      if (this.sendType===1){
        if ((this.currAddress.province+'-'+this.currAddress.city)===(this.currSupplier.province+'-'+this.currSupplier.city)){
          let $this = this
          $this.MyRequest($this.ApiDoNameShop + 'SupplierOrder/getSendData', {supplierId: this.currSupplier.id,shopAddressId:this.currAddress.id}, function (sendData) {
            console.log('sendData',sendData)
            $this.sendDistance=(sendData.sendDistance*0.001).toFixed(1)
            $this.sendPrice=sendData.sendPrice
            $this.expressPrice=sendData.sendPrice
            $this.calcPrice()
          })
        }else{
          this.sendDistance=0
          this.expressPrice=this.currSupplier.expressPrice
          this.sendPrice=0
        }
      }else{
        this.sendDistance=0
        this.expressPrice=this.currSupplier.expressPrice
        this.sendPrice=0
      }
    },
    getAddress:function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameShop + 'ShopAddress/getList', {isDefault: 1}, function (addressList) {
        if (addressList && addressList.length>0){
          $this.currAddress=addressList[0]
          $this.$forceUpdate()
        }
        // console.log('data',addressList)
      })
    },
    // 获取供应商详情
    changeSupplier: function (supplier) {
      let $this = this
      $this.currSupplier.fullMinusPrice=[]
      $this.fullMinusPrice=0
      $this.expressPrice=0
      $this.MyRequest($this.ApiDoNameShop + 'Supplier/getDetail', {id: supplier.id}, function (data) {
        $this.currSupplier = data
        $this.currSupplierId = supplier.id
        $this.allList.forEach(function (value, index) {
          if ($this.currSupplierId === value.supplier.id) {
            $this.currProductList = value.productList
          }
        })
        $this.currProductList.forEach(function (value, index) {
          $this.productSelectMap[value.id]=true
        })
        $this.calcPrice()
        $this.$forceUpdate()
      })
    },
    // 计算金额
    calcPrice: function () {
      var productPrice = 0
      let $this = this
      $this.currProductList.forEach(function (value, index) {
        if ($this.productSelectMap[value.id]){
          productPrice += (value.price * value.nums).toFixed(2) - 0
          productPrice = productPrice.toFixed(2) - 0
        }
      })
      $this.productPrice = productPrice
      $this.price = productPrice

      // 满减
      var currFull = {
        full: 0,
        minus: 0,
      }
      $this.currSupplier.fullMinusPrice.forEach(function (item, index) {
        if (item.full <= $this.productPrice && item.minus > currFull.minus) {
          currFull = item
        }
      })

      $this.currFullMinus = currFull
      if ($this.currFullMinus.minus > 0) {
        $this.price = ($this.price - $this.currFullMinus.minus).toFixed(2) - 0
        $this.fullMinusPrice = $this.currFullMinus.minus
      }else{
        $this.fullMinusPrice=0
      }


      // 运费
      if ($this.sendType===0){
        if ($this.productPrice >= $this.currSupplier.freeExpressPrice) {
          $this.expressPrice = 0
        }else{
          $this.price = ($this.price + $this.currSupplier.expressPrice).toFixed(2) - 0
          $this.expressPrice = $this.currSupplier.expressPrice
        }
      }else{
        $this.price=($this.productPrice+$this.sendPrice).toFixed(2)
        $this.price=($this.price-$this.fullMinusPrice).toFixed(2)
      }
    },
    getNewPriceModel: function (productItem, key) {
      var map = this.productNewModelMap[productItem.id]
      if (map) {
        return map[key]
      } else {
        return productItem[key]
      }
    },
    chooseModel: function (productParams) {
      if (productParams.model.indexOf(',') === -1) {
        return
      }
      productParams.currModel = this.getNewPriceModel(productParams, 'model')
      let $this = this
      $this.bus.$emit('ProductChooseModelDialogCallBus', 'cartPage', productParams, function (modelData) {
        $this.allList.forEach(function (item, index) {
          $this.allList[index].supplier.select = false
          item.productList.forEach(function (_value, _index) {
            if (_value.id === productParams.id) {
              _value.model = modelData.model
              _value.price = modelData.price
              $this.$set($this.productNewModelMap, productParams.id, {
                model: modelData.model,
                price: modelData.price,
              })
            }
          })
        })

        // 同步缓存
        MyCartTools.setAllList($this.allList)
        $this.$forceUpdate()
      })
    },
    getSelectData: function () {
      let $this = this
      var selectData = {}
      $this.allList.forEach(function (item, index) {
        if (item.supplier.select) {
          selectData = item
        }
      })
      // localStorage.setItem('selectProductData', JSON.stringify(selectData))
      return selectData
    },
    // 提交-订单
    submitOrder: function () {
      this.getSelectData()
      // this.$router.push("/ConfirmOrder")
    },
    // 更改-购物车数量
    changeProductNums: function (productParams) {
      MyCartTools.setAllList(this.allList)
      this.calcPrice()
    },
    // 更改-商品-数量
    changeSelectNums: function (shopId) {
      let $this = this
      var keysArr = Object.keys($this.productSelectMap)
      var i = 0
      keysArr.forEach(function (key, index) {
        if ($this.productSelectMap[key]) {
          i++
        }
      })
      $this.shopSelectArr = []
      $this.allList.forEach(function (item, index) {
        item.productList.forEach(function (_value, _index) {
          if ($this.productSelectMap[_value.id] === true) {
            if ($this.shopSelectArr.indexOf(item.supplier.id) === -1) {
              $this.shopSelectArr.push(item.supplier.id)
            }
          }
        })
      })
      $this.selectedNums = i

      $this.handleCacheToList()
      $this.calcPrice()
      $this.$forceUpdate()
    },
    // 返回重新查看【供应商商品】
    searchSupplierProduct:function (supplier) {
      this.$router.push({
        path:'/SupplierProductSearchPage',
        query:{
          supplierId:supplier.id
        }
      })
    },
    // 删除-单个店铺-所有商品
    delSupplier: function (supplier,index) {
      MyCartTools.delSupplier(supplier.id)
      this.calcPrice()
      this.$delete(this.allList, index)
    },
    // 删除-单个商品
    delItem: function (product) {
      MyCartTools.delProduct(product.id, product.model)
      this.allList = MyCartTools.getAllList()
      this.handleCacheToList()
      this.calcPrice()
      this.$forceUpdate()
    },
    // 处理缓存列表
    handleCacheToList: function () {
      let $this = this
      $this.allList.forEach(function (item, index) {
        $this.allList[index].supplier.select = false
        item.productList.forEach(function (_value, _index) {
          $this.allList[index].productList[_index].select = true
          $this.$set($this.productSelectMap, _value.id, true)
        })

        if (item.supplier.id===$this.currSupplierId){
          $this.currProductList=item.productList
        }
      })
      $this.selectedNums = 0
      // 默认切换
      if ($this.currSupplierId===0){
        $this.changeSupplier($this.allList[0].supplier)
      }
      $this.$forceUpdate()
    },
    // 提交订单
    submit:function () {
      let $this=this
      if ($this.sendType!==2){
        if (!$this.currAddress || !$this.currAddress.id){
          return $this.$message.error("地址信息不能为空")
        }
      }
      this.$confirm('您确认要进行该操作吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var form={
          sendTime:$this.sendType===1?$this.sendTime:'',
          sendType:$this.sendType,
          addressId:$this.sendType!==2?$this.currAddress.id:0,
          supplierId:$this.currSupplierId,
          productBuyNumsList:[],
          info:$this.info
        }
        console.log('form1',form)
        $this.currProductList.forEach(function (value,index) {
          if ($this.productSelectMap[value.id]){
            form.productBuyNumsList.push({
              shopProductStockId:value.id,
              id:value.productId,
              nums:value.nums,
              model:value.model,
            })
          }
        })
        form.productBuyNumsList=JSON.stringify(form.productBuyNumsList)
        $this.MyRequest($this.ApiDoNameShop+'SupplierOrder/submit',form,function (data) {
          $this.$message.success("提交成功")
          $this.clearSubmitProduct()
          $this.$router.push("/SupplierOrderListPage")
        })
        // alert(JSON.stringify(form))
        // productNumsList
      }).catch(() => {

      });
    },
    clearSubmitProduct:function () {
      let $this=this
      $this.currProductList.forEach(function (value,index) {
        if ($this.productSelectMap[value.id]){
          MyCartTools.delProduct(value.id, value.model)
        }
      })
    }
  }
}
</script>

<style scoped>
.other-box{ position: relative}
.other-box>.address{
  width: 545px;
  height: 100px;
  padding: 5px;
  float: left;
}
.other-box>.address-disable{
  position: absolute;
  width: 405px;
  height: 100px;
  background:rgba(0,0,0,.6);
  top: 5px;
  color: #FFFFFF;
  line-height: 100px;
  font-size: 14px;
  text-align: center;
  border-radius: 5px;
}
.other-box>.info{
  padding-top: 10px;
  width: 400px;
  float: left;
  height: 80px;
}
.total-box {
  padding-top: 10px;
  width: 220px;
  float: left;
  height: 100px;
}

.total-box .row {
  width: 100%;
  text-align: right;
  line-height: 25px;
}

.total-box .row .name {
  width: 100px;
  float: right;
  text-align: center;
}

.total-box .row .value {
  width: 115px;
  float: right;
  text-align: center;
  color: #c21717;
  font-weight: bold
}

.nav-button{}
.nav-button .button-box{ display: inline-block; padding: 0px 20px; position: relative; height: 30px; line-height: 35px;}
.nav-button .button-box i.el-icon-remove{ position: absolute; top: 0px; right: 12px; z-index: 999; color: #e02a2a; font-size: 14px;}
.nav-button .button-box i.el-icon-view{ font-size: 14px; color: #1E9FFF;cursor: pointer}
.nav-button .button-box i.el-icon-view:hover{ color: #2597a6;}
.nav-button .button-box i{}
</style>
